
package net.swa.dewei.service.impl;

import net.swa.dewei.beans.entity.DingDan;
import net.swa.dewei.beans.entity.FuwuZhan;
import net.swa.dewei.beans.entity.MenDian;
import net.swa.dewei.beans.vo.GroupAndMaxId;
import net.swa.dewei.beans.vo.VoMaxIdStateCount;
import net.swa.dewei.service.DingDanService;
import net.swa.system.dao.HibernateDaoSupport;
import net.swa.util.BuzConst;
import net.swa.util.DateUtils;
import net.swa.util.JsonResult;
import net.swa.util.io.ExcelUtil;
import net.swa.util.io.enums.MsOfficeVersion;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.StringType;
import org.springframework.stereotype.Service;

@Service("dingDanService")
public class DingDanServiceImpl extends HibernateDaoSupport implements DingDanService
{
    private static final Logger log = Logger.getLogger(DingDanServiceImpl.class);

    public String add(final DingDan m)
    {
        final String d = DateUtils.getCurrDate("yyyyMMddHHmmss");
        String r = null;
        getCurrentSession().save(m);
        r = d + m.getId();
        m.setDingDanUid(d + m.getId());
        getCurrentSession().update(m);
        return r;
    }

    public DingDan addDingdan(final DingDan m)
    {
        final String d = DateUtils.getCurrDate("yyyyMMddHHmmss");
        Session session = getCurrentSession();
        String r = null;
        session.save(m);
        r = d + m.getId();
        m.setDingDanUid(r);
        session.update(m);
        if (null != m.getMendianId())
        {
            log.debug("门店id 不为空时候，把门店imgurl返回");
            MenDian mendian = (MenDian) session.get(MenDian.class, m.getMendianId());
            if (null != mendian)
            {
                if (!StringUtils.isBlank(mendian.getImageUrl()))
                {
                    m.setMendianImageUrl(mendian.getImageUrl());
                    log.debug("门店id 不为空时候，把门店imgurl返回,success:" + mendian.getImageUrl());
                }
            }
        }
        return m;
    }

    public void delete(final Long[] ids)
    {

        Query query = getCurrentSession().createQuery("delete from DingDan  where id=:id");
        for (int i = 0; i < ids.length; i++)
        {
            if (null != ids[i])
            {
                query.setLong("id", ids[i]);
                query.executeUpdate();
            }

        }

    }

    @Override
    public boolean updateOrderStatus(final Long id , final String status)
    {
        Query query = getCurrentSession().createQuery("update DingDan set state=:state  where id=:id");
        query.setLong("id", id);
        query.setString("state", status);
        query.executeUpdate();
        return true;
    }

    @Override
    public boolean updateAssign(final Long id , final Long shopId)
    {
        Query query = getCurrentSession().createQuery("update DingDan set mendianId=:mendianId,state=:state  where id=:id");
        query.setLong("id", id);
        query.setLong("mendianId", shopId);
        query.setString("state", "2");
        query.executeUpdate();
        return true;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<DingDan> queryMyDingdans(final Long mid)
    {
        Query query = getCurrentSession().createQuery("from  DingDan  where mendianId=:mid and state in('0','2','4','5') order by id desc");
        query.setLong("mid", mid);
        query.setMaxResults(100);// 暂写死
        List<DingDan> list = query.list();
        return list;
    }

    @Override
    public void updateStatus(final Long id , final String state)
    {
        Query query = getCurrentSession().createQuery("update  DingDan  set state=:state where id=:id");
        query.setLong("id", id);
        query.setString("state", state);
        query.executeUpdate();
    }

    @Override
    public boolean updateState(final DingDan model)
    {
        StringBuilder sb = new StringBuilder();
        sb.append("update DingDan set state=:state ");
        if (null != model.getMendianId())
        {
            sb.append(",mendianId=:mendianId ");
        }
        sb.append("  where id=:id");

        Query query = getCurrentSession().createQuery(sb.toString());

        query.setLong("id", model.getId());
        if (null != model.getMendianId())
        {
            query.setLong("mendianId", model.getMendianId());
        }
        query.setString("state", model.getState());
        query.executeUpdate();
        return true;
    }

    public Boolean doTask()
    {
        Date guoqiDate = DateUtils.addHOUR(-BuzConst.HOUR48, new Date());// 2天前现在时间
        final String date = DateUtils.getDateString(guoqiDate, "yyyy-MM-dd HH:mm:ss");
        String hql = "update DingDan  set state=:state  where crateDate<=:date and state=:oldState";
        Query query = getCurrentSession().createQuery(hql);
        query.setString("state", BuzConst.DINGDAN_STATES4);
        query.setString("oldState", BuzConst.DINGDAN_STATES0);
        query.setString("date", date);
        int count = query.executeUpdate();
        log.debug("更新" + count + "条订单记录状态为超期");
        return true;
    }

    @SuppressWarnings("unchecked")
    @Override
    public HSSFWorkbook exportExcel(final String dingDanUid , final String state , final String changeType , final Long fuwuZhanId)
    {
        FuwuZhan fuwuzhan = null;
        if (null != fuwuZhanId)
        {
            fuwuzhan = (FuwuZhan) getCurrentSession().get(FuwuZhan.class, fuwuZhanId);
        }
        List<DingDan> list = new ArrayList<DingDan>();
        StringBuilder sql = new StringBuilder();
        Query query = null;

        sql
                .append("select t.address,t.changeType,t.chexingId, t.chexingName,t.city,t.crateDate,t.dianchiId,dingDanUid, t.id,t.imageUrl, t.kehuName,t.blat,t.blng,t.lat,t.lng,t.lxTel,m.lxrTel  as  menDianTel,m.address  as  mendianAddr,t.mendianId,m.lxr as  mendianLxr, m.name as mendianName, t.pinPai, t.price, t.province, t.state, t.time, t.town, t.updateDate, t.userId, t.xingHao,t.detailInfo,t.licheng,t.zhongliang,t.marketPrice,t.serverPrice,f.id as fuwuzhanId,f.name as fuwuzhanName   from  t_DingDan t  left join  t_MenDian m on m.id=t.mendianId  left join t_FuwuZhan f on f.id=m.fuwuzhanId  where 1=1");

        //        sql.append("select t.* from  t_DingDan t join t_DianChi r on r.id=t.dianchiId  where 1=1 ");
        if (!StringUtils.isBlank(dingDanUid))
        {
            sql.append(" and t.dingDanUid like :dingDanUid");
        }
        if (!StringUtils.isBlank(state))
        {
            sql.append(" and t.state=:state");
        }
        if (!StringUtils.isBlank(changeType))
        {
            sql.append(" and t.changeType=:changeType");
        }
        if (null != fuwuzhan)
        {
            sql.append(" and (m.fuwuzhanId=:fuwuzhanId ");
            if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
            {
                sql.append(" or (");
                sql.append("  t.province like :province");
                if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                {
                    sql.append(" and t.city like :city");
                    if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                    {
                        sql.append(" and t.town like :town");
                    }
                }
                sql.append(" ))");
            }
        }
        sql.append(" order by id desc");
        query = getCurrentSession().createSQLQuery(sql.toString()).addScalar("address", StandardBasicTypes.STRING).addScalar("changeType", StandardBasicTypes.STRING).addScalar("chexingId", StandardBasicTypes.LONG).addScalar("chexingName", StandardBasicTypes.STRING).addScalar("city", StandardBasicTypes.STRING).addScalar("crateDate", StandardBasicTypes.STRING).addScalar("dianchiId", StandardBasicTypes.LONG).addScalar("dingDanUid", StandardBasicTypes.STRING).addScalar("id", StandardBasicTypes.LONG).addScalar(
                "imageUrl", StandardBasicTypes.STRING).addScalar("kehuName", StandardBasicTypes.STRING).addScalar("blat", StandardBasicTypes.DOUBLE).addScalar("blng", StandardBasicTypes.DOUBLE).addScalar("lat", StandardBasicTypes.DOUBLE).addScalar("lng", StandardBasicTypes.DOUBLE).addScalar("lxTel", StandardBasicTypes.STRING).addScalar("menDianTel", StandardBasicTypes.STRING).addScalar("mendianAddr", StandardBasicTypes.STRING).addScalar("mendianId", StandardBasicTypes.LONG).addScalar("mendianLxr",
                StandardBasicTypes.STRING).addScalar("mendianName", StandardBasicTypes.STRING).addScalar("pinPai", StandardBasicTypes.STRING).addScalar("price", StandardBasicTypes.STRING).addScalar("province", StandardBasicTypes.STRING).addScalar("state", StandardBasicTypes.STRING).addScalar("time", StandardBasicTypes.STRING).addScalar("town", StandardBasicTypes.STRING).addScalar("updateDate", StandardBasicTypes.STRING).addScalar("userId", StandardBasicTypes.STRING).addScalar("xingHao", StandardBasicTypes.STRING)
                .addScalar("detailInfo", StandardBasicTypes.STRING).addScalar("licheng", StandardBasicTypes.STRING).addScalar("zhongliang", StandardBasicTypes.STRING).addScalar("marketPrice", StandardBasicTypes.STRING).addScalar("serverPrice", StandardBasicTypes.STRING).addScalar("fuwuzhanId", StandardBasicTypes.LONG).addScalar("fuwuzhanName", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(DingDan.class));
        if (!StringUtils.isBlank(dingDanUid))
        {
            query.setString("dingDanUid", "%" + dingDanUid + "%");
        }
        if (!StringUtils.isBlank(state))
        {
            query.setString("state", state);
        }
        if (!StringUtils.isBlank(changeType))
        {
            query.setString("changeType", changeType);
        }
        if (null != fuwuzhan)
        {
            query.setLong("fuwuzhanId", fuwuZhanId);
            if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
            {
                query.setString("province", fuwuzhan.getProvince() + "%");
                if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                {
                    query.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                    if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                    {
                        query.setString("town", fuwuzhan.getTown() + "%");
                    }
                }
            }

        }
        query.setMaxResults(BuzConst.MAX_RESULT);
        list = query.list();
        HSSFWorkbook book = null;
        if (null != list && list.size() > 0)
        {
            for (DingDan o : list)
            {
                o.setState(getStateinfo(o.getState()));
            }
            // 要从对象中获取的属性名
            String fieldNames[] = { "id", "dingDanUid", "chexingName", "pinPai", "xingHao", "price", "changeType", "kehuName", "lxTel", "address", "time", "crateDate", "updateDate", "state" };
            String titleNames[] = { "编号", "订单号", "车型名称", "电池品牌", "电池型号", "价格（元）", "更换方式", "客户名称", "联系电话", "联系地址", "预约时间", "下单时间", "处理时间", "状态" };

            try
            {
                book = ExcelUtil.writeToExcelFile(list, fieldNames, titleNames, 0, 0, "filename", "sheetname", true, null, MsOfficeVersion.Office2003, null);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        return book;
    }

    // 将状态代码转换
    private String getStateinfo(String state)
    {
        if (state.equals(BuzConst.DINGDAN_STATES0))
        {
            return "下单";
        }
        else if (state.equals(BuzConst.DINGDAN_STATES1))
        {
            return "完成";
        }
        else if (state.equals(BuzConst.DINGDAN_STATES2))
        {
            return "指派";
        }
        else if (state.equals(BuzConst.DINGDAN_STATES3))
        {
            return "作废";
        }
        else if (state.equals(BuzConst.DINGDAN_STATES4))
        {
            return "超期";
        }
        else if (state.equals(BuzConst.DINGDAN_STATES5))
        {
            return "核实";
        }
        else
        {
            return null;
        }

    }

    @Override
    public Map<String, ?> queryGroup(final Long fuwuzhanId)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        StringBuilder sql = new StringBuilder();
        FuwuZhan fuwuzhan = null;
        if (null != fuwuzhanId)
        {
            fuwuzhan = (FuwuZhan) getCurrentSession().get(FuwuZhan.class, fuwuzhanId);
            if (null != fuwuzhan)
            {
                sql.append("select  t.state,count(t.id) as sum    from  t_DingDan t left join  t_MenDian m on m.id=t.mendianId   where 1=1");

                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {

                    sql.append(" and (m.fuwuzhanId like :fuwuzhanId ");
                    if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                    {
                        sql.append(" or (");
                        sql.append("  t.province like :province");
                        if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                        {
                            sql.append(" and t.city like :city");
                            if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                            {
                                sql.append(" and t.town like :town");
                            }
                        }
                        sql.append(" ))");
                    }
                }
                sql.append(" GROUP BY state ");
            }
            else
            {
                map.put("success", false);
                map.put("message", "服务站不存在");
                return map;
            }
        }
        else
        {
            sql.append("select  state,count(id) as sum   from t_dingdan   GROUP BY state");
        }
        SQLQuery ss = (SQLQuery) getCurrentSession().createSQLQuery(sql.toString()).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        ss.addScalar("state", StringType.INSTANCE);
        ss.addScalar("sum", StandardBasicTypes.INTEGER);
        if (null != fuwuzhan)
        {
            if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
            {
                ss.setLong("fuwuzhanId", fuwuzhan.getId());
                ss.setString("province", fuwuzhan.getProvince() + "%");
                if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                {
                    ss.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                    if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                    {
                        ss.setString("town", fuwuzhan.getTown() + "%");
                    }
                }
            }
        }
        List list = ss.list();
        if (null != list && list.size() > 0)
        {
            List<Map<String, Object>> l = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < list.size(); i++)
            {
                Map m = (Map) list.get(i);
                l.add(m);
            }
            map.put("result", l);
            map.put("success", true);
            map.put("message", "success");
        }
        else
        {
            map.put("success", false);
            map.put("message", "null");
        }
        return map;
    }

    @Override
    public JsonResult<DingDan> queryDingdansPage2(String customerName , String customerTel , String mendianName , String dingDanUid , String state , String changeType , Long fuwuZhanId , int currentPage , int pageSize)
    {
        FuwuZhan fuwuzhan = null;
        if (null != fuwuZhanId)
        {
            fuwuzhan = (FuwuZhan) getCurrentSession().get(FuwuZhan.class, fuwuZhanId);
        }
        JsonResult<DingDan> json = new JsonResult<DingDan>();
        List<DingDan> list = new ArrayList<DingDan>();
        StringBuilder sql = new StringBuilder();
        Query query = null;
        sql
                .append("select t.address,t.changeType,t.chexingId, t.chexingName,t.city,t.crateDate,t.dianchiId,dingDanUid, t.id,t.imageUrl, t.kehuName,t.blat,t.blng,t.lat,t.lng,t.lxTel,m.lxrTel  as  menDianTel,m.address  as  mendianAddr,t.mendianId,m.lxr as  mendianLxr, m.name as mendianName, t.pinPai, t.price, t.province, t.state, t.time, t.town, t.updateDate, t.userId, t.xingHao,t.detailInfo,t.licheng,t.zhongliang,t.marketPrice,t.serverPrice,f.id as fuwuzhanId,f.name as fuwuzhanName    from  t_DingDan t  left join  t_MenDian m on m.id=t.mendianId  left join t_FuwuZhan f on f.id=m.fuwuzhanId   where 1=1 ");
        if (!StringUtils.isBlank(dingDanUid))
        {
            sql.append(" and t.dingDanUid like :dingDanUid");
        }
        if (!StringUtils.isBlank(customerName))
        {
            sql.append(" and t.kehuName like :customerName");
        }
        if (!StringUtils.isBlank(customerTel))
        {
            sql.append(" and t.lxTel like :customerTel");
        }
        if (!StringUtils.isBlank(mendianName))
        {
            sql.append(" and m.name like :mendianName");
        }
        if (!StringUtils.isBlank(state))
        {
            sql.append(" and t.state=:state");
        }
        if (!StringUtils.isBlank(changeType))
        {
            sql.append(" and t.changeType=:changeType");
        }

        if (null != fuwuzhan)
        {
            sql.append(" and (m.fuwuzhanId=:fuwuzhanId ");
            if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
            {
                sql.append(" or (t.changeType<>'附近门店更换'  and  ");
                sql.append("  t.province=:province");
                if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                {
                    sql.append(" and t.city=:city");
                    if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                    {
                        sql.append(" and t.town=:town");
                    }
                }
                sql.append(" ))");
            }
        }
        query = getCurrentSession().createSQLQuery(sql.toString() + " order by id desc").addScalar("address", StandardBasicTypes.STRING).addScalar("changeType", StandardBasicTypes.STRING).addScalar("chexingId", StandardBasicTypes.LONG).addScalar("chexingName", StandardBasicTypes.STRING).addScalar("city", StandardBasicTypes.STRING).addScalar("crateDate", StandardBasicTypes.STRING).addScalar("dianchiId", StandardBasicTypes.LONG).addScalar("dingDanUid", StandardBasicTypes.STRING).addScalar("id",
                StandardBasicTypes.LONG).addScalar("imageUrl", StandardBasicTypes.STRING).addScalar("kehuName", StandardBasicTypes.STRING).addScalar("blat", StandardBasicTypes.DOUBLE).addScalar("blng", StandardBasicTypes.DOUBLE).addScalar("lat", StandardBasicTypes.DOUBLE).addScalar("lng", StandardBasicTypes.DOUBLE).addScalar("lxTel", StandardBasicTypes.STRING).addScalar("menDianTel", StandardBasicTypes.STRING).addScalar("mendianAddr", StandardBasicTypes.STRING).addScalar("mendianId", StandardBasicTypes.LONG)
                .addScalar("mendianLxr", StandardBasicTypes.STRING).addScalar("mendianName", StandardBasicTypes.STRING).addScalar("pinPai", StandardBasicTypes.STRING).addScalar("price", StandardBasicTypes.STRING).addScalar("province", StandardBasicTypes.STRING).addScalar("state", StandardBasicTypes.STRING).addScalar("time", StandardBasicTypes.STRING).addScalar("town", StandardBasicTypes.STRING).addScalar("updateDate", StandardBasicTypes.STRING).addScalar("userId", StandardBasicTypes.STRING).addScalar("xingHao",
                        StandardBasicTypes.STRING).addScalar("detailInfo", StandardBasicTypes.STRING).addScalar("licheng", StandardBasicTypes.STRING).addScalar("zhongliang", StandardBasicTypes.STRING).addScalar("marketPrice", StandardBasicTypes.STRING).addScalar("serverPrice", StandardBasicTypes.STRING).addScalar("fuwuzhanId", StandardBasicTypes.LONG).addScalar("fuwuzhanName", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(DingDan.class));
        if (!StringUtils.isBlank(dingDanUid))
        {
            query.setString("dingDanUid", "%" + dingDanUid.trim() + "%");
        }
        if (!StringUtils.isBlank(customerName))
        {
            query.setString("customerName", "%" + customerName.trim() + "%");
        }
        if (!StringUtils.isBlank(customerTel))
        {
            query.setString("customerTel", "%" + customerTel.trim() + "%");
        }
        if (!StringUtils.isBlank(mendianName))
        {
            query.setString("mendianName", "%" + mendianName.trim() + "%");
        }
        if (!StringUtils.isBlank(state))
        {
            query.setString("state", state);
        }
        if (!StringUtils.isBlank(changeType))
        {
            query.setString("changeType", changeType);
        }
        if (null != fuwuzhan)
        {
            query.setLong("fuwuzhanId", fuwuZhanId);

            if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
            {
                query.setString("province", fuwuzhan.getProvince());
                if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                {
                    query.setString("city", fuwuzhan.getCity().replace("市", ""));
                    if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                    {
                        query.setString("town", fuwuzhan.getTown());
                    }
                }
            }
        }
        if (pageSize > 0)
        {
            int from = (currentPage - 1) * pageSize;
            query.setFirstResult(from);
            query.setMaxResults(pageSize);
        }
        list = (List<DingDan>) query.list();
        query = getCurrentSession().createSQLQuery("select count(*) as counNum from (" + sql.toString() + ") as d").addScalar("counNum", StandardBasicTypes.INTEGER);
        if (!StringUtils.isBlank(dingDanUid))
        {
            query.setString("dingDanUid", "%" + dingDanUid + "%");
        }
        if (!StringUtils.isBlank(customerName))
        {
            query.setString("customerName", "%" + customerName.trim() + "%");
        }
        if (!StringUtils.isBlank(customerTel))
        {
            query.setString("customerTel", "%" + customerTel.trim() + "%");
        }
        if (!StringUtils.isBlank(mendianName))
        {
            query.setString("mendianName", "%" + mendianName.trim() + "%");
        }
        if (!StringUtils.isBlank(state))
        {
            query.setString("state", state);
        }
        if (!StringUtils.isBlank(changeType))
        {
            query.setString("changeType", changeType);
        }
        if (null != fuwuzhan)
        {
            query.setLong("fuwuzhanId", fuwuZhanId);
            if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
            {
                query.setString("province", fuwuzhan.getProvince());
                if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                {
                    query.setString("city", fuwuzhan.getCity().replace("市", ""));
                    if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                    {
                        query.setString("town", fuwuzhan.getTown());
                    }
                }
            }
        }
        if (pageSize > 0)
        {
            int totalCount = (Integer) query.uniqueResult();
            int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
            json.setTotalSize(totalCount);
            json.setTotalPage(totalPage);
            json.setPageSize(pageSize);
            json.setCurrentPage(currentPage);
        }
        if (null != list && list.size() > 0)
        {
            for (DingDan o : list)
            {
                if (!StringUtils.isBlank(o.getCrateDate()))
                {
                    o.setInvalidDate(DateUtils.getDatePlusHour(o.getCrateDate(), BuzConst.FORMAT_STRING1, BuzConst.FORMAT_STRING2, BuzConst.HOUR48));
                }
            }
        }
        json.setResult(list);
        return json;
    }

    @Override
    public JsonResult<DingDan> queryDingdansPage3(String customerName , String customerTel , String mendianName , String dingDanUid , String state , String changeType , Long fuwuZhanId , String fuwuzhanName , int currentPage , int pageSize , String orderBy , String orderType)
    {
        JsonResult<DingDan> json = new JsonResult<DingDan>();
        List<DingDan> list = new ArrayList<DingDan>();
        StringBuilder sql = new StringBuilder();
        StringBuilder countsql = new StringBuilder();
        Query query = null;

        String fwzIds = null;
        StringBuilder fwzStr = new StringBuilder();
        FuwuZhan fuwuzhan = null;
        if (null != fuwuZhanId)
        {
            fuwuzhan = (FuwuZhan) getCurrentSession().get(FuwuZhan.class, fuwuZhanId);
        }
        else if (!StringUtils.isBlank(fuwuzhanName))
        {
            if (StringUtils.isBlank(state) || state.equals(BuzConst.DINGDAN_STATES0) || state.equals(BuzConst.DINGDAN_STATES3) || state.equals(BuzConst.DINGDAN_STATES4))
            {
                String hq = "from FuwuZhan where  name like :name";
                Query qq = getCurrentSession().createQuery(hq);
                qq.setString("name", "%" + fuwuzhanName + "%");
                List<FuwuZhan> flist = qq.list();
                if (null != flist && flist.size() > 0)
                {
                    fwzIds = "";
                    if (StringUtils.isBlank(state))
                    {
                        fwzStr.append("or (t.changeType<>'附近门店更换' and t.state in ('0','3','4') and t.mendianId is null  and(");
                    }
                    else
                    {
                        fwzStr.append("or (t.changeType<>'附近门店更换' and t.state='" + state + "' and t.mendianId is null   and(");
                    }
                    for (int i = 0; i < flist.size(); i++)
                    {
                        FuwuZhan f = flist.get(i);
                        if ((i + 1) == flist.size())
                        {
                            fwzIds += f.getId();
                            if (!StringUtils.isBlank(f.getProvince()) && (!"请选择".equals(f.getProvince())))
                            {
                                fwzStr.append("(t.province like '" + f.getProvince() + "%' ");
                                if (!StringUtils.isBlank(f.getCity()) && (!"请选择".equals(f.getCity())))
                                {
                                    fwzStr.append(" and t.city like '" + f.getCity().replace("市", "") + "%' ");
                                    if (!StringUtils.isBlank(f.getTown()) && (!"请选择".equals(f.getTown())))
                                    {
                                        fwzStr.append(" and t.town like '" + f.getTown() + "%' ");
                                    }
                                }
                                fwzStr.append(" )");
                            }
                            fwzStr.append(" ))");
                        }
                        else
                        {
                            fwzIds += f.getId() + ",";
                            if (!StringUtils.isBlank(f.getProvince()) && (!"请选择".equals(f.getProvince())))
                            {
                                fwzStr.append("(t.province like '" + f.getProvince() + "%' ");
                                if (!StringUtils.isBlank(f.getCity()) && (!"请选择".equals(f.getCity())))
                                {
                                    fwzStr.append(" and t.city like '" + f.getCity().replace("市", "") + "%' ");
                                    if (!StringUtils.isBlank(f.getTown()) && (!"请选择".equals(f.getTown())))
                                    {
                                        fwzStr.append(" and t.town like '" + f.getTown() + "%' ) or ");
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    return json;
                }
            }
            else
            {
                fwzIds = null;
                fwzStr.append(" and f.name like '%" + fuwuzhanName + "%' ");
            }
        }

        sql
                .append("select t.address,t.changeType,t.chexingId, t.chexingName,t.city,t.crateDate,t.dianchiId,dingDanUid, t.id,t.imageUrl, t.kehuName,t.blat,t.blng,t.lat,t.lng,t.lxTel,m.lxrTel  as  menDianTel,m.address  as  mendianAddr,t.mendianId,m.lxr as  mendianLxr, m.name as mendianName, t.pinPai, t.price, t.province, t.state, t.time, t.town, t.updateDate, t.userId, t.xingHao,t.detailInfo,t.licheng,t.zhongliang,t.marketPrice,t.serverPrice,f.id as fuwuzhanId,f.name as fuwuzhanName  from  t_DingDan t  left join  t_MenDian m on m.id=t.mendianId  left join t_FuwuZhan f on f.id=m.fuwuzhanId  where 1=1 ");

        countsql.append("select  count(*) as counNum    from  t_DingDan t  left join  t_MenDian m on m.id=t.mendianId  left join t_FuwuZhan f on f.id=m.fuwuzhanId  where 1=1 ");

        if (!StringUtils.isBlank(dingDanUid))
        {
            sql.append(" and t.dingDanUid like :dingDanUid");
            countsql.append(" and t.dingDanUid like :dingDanUid");
        }
        if (!StringUtils.isBlank(customerName))
        {
            sql.append(" and t.kehuName like :customerName");
            countsql.append(" and t.kehuName like :customerName");
        }
        if (!StringUtils.isBlank(customerTel))
        {
            sql.append(" and t.lxTel like :customerTel");
            countsql.append(" and t.lxTel like :customerTel");
        }
        if (!StringUtils.isBlank(mendianName))
        {
            sql.append(" and m.name like :mendianName");
            countsql.append(" and m.name like :mendianName");
        }
        if (!StringUtils.isBlank(state))
        {
            sql.append(" and t.state=:state ");
            countsql.append(" and t.state=:state ");
        }
        if (!StringUtils.isBlank(changeType))
        {
            sql.append(" and t.changeType=:changeType ");
            countsql.append(" and t.changeType=:changeType ");
        }

        if (null != fuwuzhan)
        {
            sql.append(" and (m.fuwuzhanId=:fuwuzhanId ");
            countsql.append(" and (m.fuwuzhanId=:fuwuzhanId ");
            if (StringUtils.isBlank(state) || state.equals(BuzConst.DINGDAN_STATES0) || state.equals(BuzConst.DINGDAN_STATES3) || state.equals(BuzConst.DINGDAN_STATES4))
            {
                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    if (StringUtils.isBlank(state))
                    {
                        sql.append(" or (t.changeType<>'附近门店更换' and t.state in('0','3','4') and t.mendianId is null  and  ");
                        countsql.append(" or (t.changeType<>'附近门店更换' and t.state in('0','3','4') and t.mendianId is null  and  ");
                    }
                    else
                    {
                        sql.append(" or (t.changeType<>'附近门店更换' and t.state='" + state + "' and t.mendianId is null   and  ");
                        countsql.append(" or (t.changeType<>'附近门店更换' and t.state='" + state + "' and t.mendianId is null   and  ");
                    }
                    sql.append("  t.province like :province");
                    countsql.append("  t.province like :province");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                    {
                        sql.append(" and t.city like :city");
                        countsql.append(" and t.city like :city");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                        {
                            sql.append(" and t.town like :town");
                            countsql.append(" and t.town like :town");
                        }
                    }
                    sql.append(" )");
                    countsql.append(" )");
                }
            }
            sql.append(" )");
            countsql.append(" )");
        }
        else
        {
            if (!StringUtils.isBlank(fwzIds))
            {
                sql.append(" and (f.id in (" + fwzIds + ") " + fwzStr + ") ");
                countsql.append(" and (f.id in (" + fwzIds + ") " + fwzStr + ") ");
            }
            else if (null == fwzIds && fwzStr.length() > 0)
            {
                sql.append("  " + fwzStr);
                countsql.append("  " + fwzStr);
            }
        }
        String rsql = sql.toString();
        if (!StringUtils.isBlank(orderBy))
        {
            rsql += " order by " + orderBy;
            if (!StringUtils.isBlank(orderType))
            {
                rsql += "  " + orderType;
            }
        }
        else
        {
            rsql += " order by id desc ";
        }
        query = getCurrentSession().createSQLQuery(rsql).addScalar("address", StandardBasicTypes.STRING).addScalar("changeType", StandardBasicTypes.STRING).addScalar("chexingId", StandardBasicTypes.LONG).addScalar("chexingName", StandardBasicTypes.STRING).addScalar("city", StandardBasicTypes.STRING).addScalar("crateDate", StandardBasicTypes.STRING).addScalar("dianchiId", StandardBasicTypes.LONG).addScalar("dingDanUid", StandardBasicTypes.STRING).addScalar("id", StandardBasicTypes.LONG).addScalar("imageUrl",
                StandardBasicTypes.STRING).addScalar("kehuName", StandardBasicTypes.STRING).addScalar("blat", StandardBasicTypes.DOUBLE).addScalar("blng", StandardBasicTypes.DOUBLE).addScalar("lat", StandardBasicTypes.DOUBLE).addScalar("lng", StandardBasicTypes.DOUBLE).addScalar("lxTel", StandardBasicTypes.STRING).addScalar("menDianTel", StandardBasicTypes.STRING).addScalar("mendianAddr", StandardBasicTypes.STRING).addScalar("mendianId", StandardBasicTypes.LONG).addScalar("mendianLxr", StandardBasicTypes.STRING)
                .addScalar("mendianName", StandardBasicTypes.STRING).addScalar("pinPai", StandardBasicTypes.STRING).addScalar("price", StandardBasicTypes.STRING).addScalar("province", StandardBasicTypes.STRING).addScalar("state", StandardBasicTypes.STRING).addScalar("time", StandardBasicTypes.STRING).addScalar("town", StandardBasicTypes.STRING).addScalar("updateDate", StandardBasicTypes.STRING).addScalar("userId", StandardBasicTypes.STRING).addScalar("xingHao", StandardBasicTypes.STRING).addScalar("detailInfo",
                        StandardBasicTypes.STRING).addScalar("licheng", StandardBasicTypes.STRING).addScalar("zhongliang", StandardBasicTypes.STRING).addScalar("marketPrice", StandardBasicTypes.STRING).addScalar("serverPrice", StandardBasicTypes.STRING).addScalar("fuwuzhanId", StandardBasicTypes.LONG).addScalar("fuwuzhanName", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(DingDan.class));

        if (!StringUtils.isBlank(dingDanUid))
        {
            query.setString("dingDanUid", "%" + dingDanUid.trim() + "%");
        }
        if (!StringUtils.isBlank(customerName))
        {
            query.setString("customerName", "%" + customerName.trim() + "%");
        }
        if (!StringUtils.isBlank(customerTel))
        {
            query.setString("customerTel", "%" + customerTel.trim() + "%");
        }
        if (!StringUtils.isBlank(mendianName))
        {
            query.setString("mendianName", "%" + mendianName.trim() + "%");
        }
        if (!StringUtils.isBlank(state))
        {
            query.setString("state", state);
        }
        if (!StringUtils.isBlank(changeType))
        {
            query.setString("changeType", changeType);
        }
        if (null != fuwuzhan)
        {
            query.setLong("fuwuzhanId", fuwuZhanId);
            if (StringUtils.isBlank(state) || state.equals(BuzConst.DINGDAN_STATES0) || state.equals(BuzConst.DINGDAN_STATES3) || state.equals(BuzConst.DINGDAN_STATES4))
            {
                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    query.setString("province", fuwuzhan.getProvince() + "%");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                    {
                        query.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                        {
                            query.setString("town", fuwuzhan.getTown() + "%");
                        }
                    }
                }
            }
        }
        if (pageSize > 0)
        {
            int from = (currentPage - 1) * pageSize;
            query.setFirstResult(from);
            query.setMaxResults(pageSize);
        }
        list = (List<DingDan>) query.list();
        query = getCurrentSession().createSQLQuery(countsql.toString()).addScalar("counNum", StandardBasicTypes.INTEGER);
        if (!StringUtils.isBlank(dingDanUid))
        {
            query.setString("dingDanUid", "%" + dingDanUid + "%");
        }
        if (!StringUtils.isBlank(customerName))
        {
            query.setString("customerName", "%" + customerName.trim() + "%");
        }
        if (!StringUtils.isBlank(customerTel))
        {
            query.setString("customerTel", "%" + customerTel.trim() + "%");
        }
        if (!StringUtils.isBlank(mendianName))
        {
            query.setString("mendianName", "%" + mendianName.trim() + "%");
        }
        if (!StringUtils.isBlank(state))
        {
            query.setString("state", state);
        }
        if (!StringUtils.isBlank(changeType))
        {
            query.setString("changeType", changeType);
        }
        if (null != fuwuzhan)
        {
            query.setLong("fuwuzhanId", fuwuZhanId);
            if (StringUtils.isBlank(state) || state.equals(BuzConst.DINGDAN_STATES0) || state.equals(BuzConst.DINGDAN_STATES3) || state.equals(BuzConst.DINGDAN_STATES4))
            {
                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    query.setString("province", fuwuzhan.getProvince() + "%");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                    {
                        query.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                        {
                            query.setString("town", fuwuzhan.getTown() + "%");
                        }
                    }
                }
            }
        }

        if (pageSize > 0)
        {
            int totalCount = (Integer) query.uniqueResult();
            int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
            json.setTotalSize(totalCount);
            json.setTotalPage(totalPage);
            json.setPageSize(pageSize);
            json.setCurrentPage(currentPage);
        }
        //根据省市县 查询服务站，多个只取1个
        String hql = null;
        if (null != list && list.size() > 0)
        {
            for (DingDan o : list)
            {
                if (!StringUtils.isBlank(o.getCrateDate()))
                {
                    o.setInvalidDate(DateUtils.getDatePlusHour(o.getCrateDate(), BuzConst.FORMAT_STRING1, BuzConst.FORMAT_STRING2, BuzConst.HOUR48));
                }
                //附上服务站
                //根据省市县 查询服务站，多个只取1个
                if ((BuzConst.DINGDAN_CHANGE_TYPE_SM.equals(o.getChangeType()) || BuzConst.DINGDAN_CHANGE_TYPE_WWD.equals(o.getChangeType())) && (StringUtils.isBlank(o.getFuwuzhanName())))
                {
                    if (!StringUtils.isBlank(o.getProvince()))
                    {
                        String p = o.getProvince();
                        if (p.length() > 3)
                        {
                            p.substring(0, 3);
                        }
                        if (!StringUtils.isBlank(o.getCity()))
                        {
                            String c = o.getCity();
                            if (c.length() > 3)
                            {
                                c.substring(0, 3);
                            }
                            if (!StringUtils.isBlank(o.getTown()))
                            {
                                String t = o.getTown();
                                if (t.length() > 3)
                                {
                                    t.substring(0, 3);
                                }
                                hql = "from   FuwuZhan   where province like :province and city like :city and town like :town ";
                                Query q = getCurrentSession().createQuery(hql);
                                q.setString("province", p + "%");
                                q.setString("city", c + "%");
                                q.setString("town", t + "%");
                                List<FuwuZhan> l = (List<FuwuZhan>) q.list();
                                if (null != l && l.size() > 0)
                                {
                                    FuwuZhan f = l.get(0);
                                    if (!StringUtils.isBlank(f.getName()))
                                    {
                                        o.setFuwuzhanId(f.getId());
                                        o.setFuwuzhanName(f.getName());
                                    }
                                }
                                else
                                {
                                    hql = "from   FuwuZhan   where province like :province and city like :city and (town ='请选择' or town is null) ";
                                    q = getCurrentSession().createQuery(hql);
                                    q.setString("province", p + "%");
                                    q.setString("city", c + "%");
                                    List<FuwuZhan> l2 = (List<FuwuZhan>) q.list();
                                    if (null != l2 && l2.size() > 0)
                                    {
                                        FuwuZhan f = l2.get(0);
                                        if (!StringUtils.isBlank(f.getName()))
                                        {
                                            o.setFuwuzhanId(f.getId());
                                            o.setFuwuzhanName(f.getName());
                                        }
                                    }
                                    else
                                    {
                                        hql = "from   FuwuZhan   where province like :province and (city ='请选择' or city is null) ";
                                        q = getCurrentSession().createQuery(hql);
                                        q.setString("province", p + "%");
                                        List<FuwuZhan> l3 = (List<FuwuZhan>) q.list();
                                        if (null != l3 && l3.size() > 0)
                                        {
                                            FuwuZhan f = l3.get(0);
                                            if (!StringUtils.isBlank(f.getName()))
                                            {
                                                o.setFuwuzhanId(f.getId());
                                                o.setFuwuzhanName(f.getName());
                                            }
                                        }
                                        else
                                        {
                                            o.setFuwuzhanName(BuzConst.DEWEI_NAME);
                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }
        }
        json.setResult(list);
        return json;
    }

    @Override
    public DingDan queryById(Long id)
    {
        StringBuilder sql = new StringBuilder();
        Query query = null;
        sql
                .append("select t.address,t.changeType,t.chexingId, t.chexingName,t.city,t.crateDate,t.dianchiId,dingDanUid, t.id,t.imageUrl, t.kehuName,t.blat,t.blng,t.lat,t.lng,t.lxTel,m.lxrTel  as  menDianTel,m.address  as  mendianAddr,t.mendianId,m.lxr as  mendianLxr, m.name as mendianName, t.pinPai, t.price, t.province, t.state, t.time, t.town, t.updateDate, t.userId, t.xingHao,t.detailInfo,t.licheng,t.zhongliang,t.marketPrice,t.serverPrice,f.id as fuwuzhanId,f.name as fuwuzhanName    from  t_DingDan t  left join  t_MenDian m on m.id=t.mendianId  left join t_FuwuZhan f on f.id=m.fuwuzhanId   where 1=1 ");
        sql.append(" and  t.id=:id");
        query = getCurrentSession().createSQLQuery(sql.toString()).addScalar("address", StandardBasicTypes.STRING).addScalar("changeType", StandardBasicTypes.STRING).addScalar("chexingId", StandardBasicTypes.LONG).addScalar("chexingName", StandardBasicTypes.STRING).addScalar("city", StandardBasicTypes.STRING).addScalar("crateDate", StandardBasicTypes.STRING).addScalar("dianchiId", StandardBasicTypes.LONG).addScalar("dingDanUid", StandardBasicTypes.STRING).addScalar("id", StandardBasicTypes.LONG).addScalar(
                "imageUrl", StandardBasicTypes.STRING).addScalar("kehuName", StandardBasicTypes.STRING).addScalar("blat", StandardBasicTypes.DOUBLE).addScalar("blng", StandardBasicTypes.DOUBLE).addScalar("lat", StandardBasicTypes.DOUBLE).addScalar("lng", StandardBasicTypes.DOUBLE).addScalar("lxTel", StandardBasicTypes.STRING).addScalar("menDianTel", StandardBasicTypes.STRING).addScalar("mendianAddr", StandardBasicTypes.STRING).addScalar("mendianId", StandardBasicTypes.LONG).addScalar("mendianLxr",
                StandardBasicTypes.STRING).addScalar("mendianName", StandardBasicTypes.STRING).addScalar("pinPai", StandardBasicTypes.STRING).addScalar("price", StandardBasicTypes.STRING).addScalar("province", StandardBasicTypes.STRING).addScalar("state", StandardBasicTypes.STRING).addScalar("time", StandardBasicTypes.STRING).addScalar("town", StandardBasicTypes.STRING).addScalar("updateDate", StandardBasicTypes.STRING).addScalar("userId", StandardBasicTypes.STRING).addScalar("xingHao", StandardBasicTypes.STRING)
                .addScalar("detailInfo", StandardBasicTypes.STRING).addScalar("licheng", StandardBasicTypes.STRING).addScalar("zhongliang", StandardBasicTypes.STRING).addScalar("marketPrice", StandardBasicTypes.STRING).addScalar("serverPrice", StandardBasicTypes.STRING).addScalar("fuwuzhanId", StandardBasicTypes.LONG).addScalar("fuwuzhanName", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(DingDan.class));
        query.setLong("id", id);
        DingDan o = (DingDan) query.uniqueResult();

        //附上服务站
        //根据省市县 查询服务站，多个只取1个
        String hql = null;
        if ((BuzConst.DINGDAN_CHANGE_TYPE_SM.equals(o.getChangeType()) || BuzConst.DINGDAN_CHANGE_TYPE_WWD.equals(o.getChangeType())) && (StringUtils.isBlank(o.getFuwuzhanName())))
        {
            if (!StringUtils.isBlank(o.getProvince()))
            {
                String p = o.getProvince();
                if (p.length() > 3)
                {
                    p.substring(0, 3);
                }
                if (!StringUtils.isBlank(o.getCity()))
                {
                    String c = o.getCity();
                    if (c.length() > 3)
                    {
                        c.substring(0, 3);
                    }
                    if (!StringUtils.isBlank(o.getTown()))
                    {
                        String t = o.getTown();
                        if (t.length() > 3)
                        {
                            t.substring(0, 3);
                        }
                        hql = "from   FuwuZhan   where province like :province and city like :city and town like :town ";
                        Query q = getCurrentSession().createQuery(hql);
                        q.setString("province", p + "%");
                        q.setString("city", c + "%");
                        q.setString("town", t + "%");
                        List<FuwuZhan> l = (List<FuwuZhan>) q.list();
                        if (null != l && l.size() > 0)
                        {
                            FuwuZhan f = l.get(0);
                            if (!StringUtils.isBlank(f.getName()))
                            {
                                o.setFuwuzhanId(f.getId());
                                o.setFuwuzhanName(f.getName());
                            }
                        }
                        else
                        {
                            hql = "from   FuwuZhan   where province like :province and city like :city and (town ='请选择' or town is null) ";
                            q = getCurrentSession().createQuery(hql);
                            q.setString("province", p + "%");
                            q.setString("city", c + "%");
                            List<FuwuZhan> l2 = (List<FuwuZhan>) q.list();
                            if (null != l2 && l2.size() > 0)
                            {
                                FuwuZhan f = l2.get(0);
                                if (!StringUtils.isBlank(f.getName()))
                                {
                                    o.setFuwuzhanId(f.getId());
                                    o.setFuwuzhanName(f.getName());
                                }
                            }
                            else
                            {
                                hql = "from   FuwuZhan   where province like :province and (city ='请选择' or city is null) ";
                                q = getCurrentSession().createQuery(hql);
                                q.setString("province", p + "%");
                                List<FuwuZhan> l3 = (List<FuwuZhan>) q.list();
                                if (null != l3 && l3.size() > 0)
                                {
                                    FuwuZhan f = l3.get(0);
                                    if (!StringUtils.isBlank(f.getName()))
                                    {
                                        o.setFuwuzhanId(f.getId());
                                        o.setFuwuzhanName(f.getName());
                                    }
                                }
                                else
                                {
                                    o.setFuwuzhanName(BuzConst.DEWEI_NAME);
                                }
                            }
                        }

                    }
                }
            }
        }
        return o;
    }

    @Override
    public List<DingDan> queryMyDingdanByUuid(Long mid , String dingDanUid)
    {
        StringBuilder sb = new StringBuilder().append("from  DingDan  where mendianId=:mid and state in('0','2','4','5') ");
        if (!StringUtils.isBlank(dingDanUid))
        {
            sb.append(" and dingDanUid=:dingDanUid  ");
        }
        sb.append("  order by id desc");
        Query query = getCurrentSession().createQuery(sb.toString());
        query.setLong("mid", mid);
        if (!StringUtils.isBlank(dingDanUid))
        {
            query.setString("dingDanUid", dingDanUid);
        }
        List<DingDan> list = query.list();
        return list;
    }

    @Override
    public GroupAndMaxId queryGroupMax(final Long fuwuzhanId , Long dingdanId , String state)
    {
        if (StringUtils.isBlank(state))
        {
            state = BuzConst.DINGDAN_STATES0;
        }
        Session session = getOpenSession();
        StringBuilder sql = new StringBuilder();
        if (null == dingdanId)
        {
            dingdanId = 0l;
        }
        FuwuZhan fuwuzhan = null;
        if (null != fuwuzhanId)
        {
            fuwuzhan = (FuwuZhan) session.get(FuwuZhan.class, fuwuzhanId);
            if (null != fuwuzhan)
            {
                sql.append("select  t.state,count(t.id) as sum,t.changeType    from  t_DingDan t left join  t_MenDian m on m.id=t.mendianId   where t.id>:dingdanId and t.changeType=:changeType and  t.state=:state  ");
                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    sql.append(" and (m.fuwuzhanId=:fuwuzhanId ");
                    if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                    {
                        sql.append(" or (");
                        sql.append("  t.province like :province");
                        if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                        {
                            sql.append(" and t.city like :city");
                            if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                            {
                                sql.append(" and t.town like :town");
                            }
                        }
                        sql.append(" ))");
                    }
                }
                sql.append(" GROUP BY changeType,state");
            }
            else
            {
                return null;
            }
        }
        else
        {
            sql.append("select  state,count(id) as sum ,changeType   from t_dingdan  where id>:dingdanId and changeType=:changeType and state=:state  GROUP BY changeType, state ");
        }

        SQLQuery ss = (SQLQuery) session.createSQLQuery(sql.toString()).addScalar("state", StringType.INSTANCE).addScalar("sum", StandardBasicTypes.INTEGER).addScalar("changeType", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(VoMaxIdStateCount.class));
        if (null != fuwuzhan)
        {
            if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
            {
                ss.setLong("fuwuzhanId", fuwuzhan.getId());
                ss.setString("province", fuwuzhan.getProvince() + "%");
                if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                {
                    ss.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                    if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                    {
                        ss.setString("town", fuwuzhan.getTown() + "%");
                    }
                }
            }
        }
        ss.setString("state", state);
        ss.setLong("dingdanId", 0l);
        ss.setString("changeType", BuzConst.DINGDAN_CHANGE_TYPE_SM);
        VoMaxIdStateCount vo = (VoMaxIdStateCount) ss.uniqueResult();
        if (null == vo)
        {
            vo = new VoMaxIdStateCount();
            vo.setChangeType(BuzConst.DINGDAN_CHANGE_TYPE_SM);
            vo.setState(state);
            vo.setNewSum(0);
            vo.setSum(0);
        }
        else
        {
            if (null != vo.getSum())
            {
                vo.setNewSum(vo.getSum());
            }
            else
            {
                vo.setNewSum(0);
            }
            if (0l != dingdanId)
            {
                ss.setLong("dingdanId", dingdanId);
                ss.setString("changeType", BuzConst.DINGDAN_CHANGE_TYPE_SM);
                VoMaxIdStateCount vo3 = (VoMaxIdStateCount) ss.uniqueResult();
                if (null != vo3)
                {
                    if (null != vo3.getSum())
                    {
                        vo.setNewSum(vo3.getSum());
                    }
                }
            }
        }
        ss.setString("changeType", BuzConst.DINGDAN_CHANGE_TYPE_MD);
        VoMaxIdStateCount vo2 = (VoMaxIdStateCount) ss.uniqueResult();
        if (null == vo2)
        {
            vo2 = new VoMaxIdStateCount();
            vo2.setChangeType(BuzConst.DINGDAN_CHANGE_TYPE_MD);
            vo.setState(state);
            vo2.setNewSum(0);
            vo2.setSum(0);
        }
        else
        {
            if (null != vo2.getSum())
            {
                vo2.setNewSum(vo2.getSum());
            }
            else
            {
                vo2.setNewSum(0);
            }
            if (0l != dingdanId)
            {
                ss.setLong("dingdanId", dingdanId);
                ss.setString("changeType", BuzConst.DINGDAN_CHANGE_TYPE_MD);
                VoMaxIdStateCount vo4 = (VoMaxIdStateCount) ss.uniqueResult();
                if (null != vo4)
                {
                    if (null != vo4.getSum())
                    {
                        vo2.setNewSum(vo4.getSum());
                    }
                }
            }
        }
        GroupAndMaxId r = new GroupAndMaxId();
        r.setNearChange(vo2);
        r.setManuChange(vo);
        ss = session.createSQLQuery("select max(id) as maxid  from t_dingdan");
        Long maxid = Long.parseLong(ss.uniqueResult().toString());
        r.setCurrentMaxId(maxid);
        if (session.isOpen())
        {
            session.close();
        }
        return r;
    }
}